package ru.xpparty.scanner;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * Scanner of one socket(host + port)
 * 
 * @author xp.party
 *
 */
public class SocketScanner {
    private String host;
    private int port;

    /**
     * Constructs new socket scanner 
     * with given host and port
     * 
     * @param host
     * @param port
     */
    public SocketScanner(String host, int port) {
        this.host = host;
        this.port = port;
    }

    /**
     * Performs scan of port
     * 
     * @return status of port
     */
    public PortStatus scan() {
        Socket socket = null;
        try {
            socket = new Socket(host, port);
            return PortStatus.OPENED;
        }        
        catch(UnknownHostException e){
            throw new UnavailableHostException(e);
        }
        catch (IOException e) {
            return PortStatus.CLOSED;
        }
        finally {
            tryClose(socket);
        }
    }

    /**
     * Tries to close socket
     * 
     * @param socket sockt to close
     */
	private void tryClose(Socket socket) {
		if (socket != null) {
		    try {
		        socket.close();
		    } catch (IOException e) {
		        throw new RuntimeException(e);
		    }
		}
	}
}
